package com.etms.service.impl;


import com.etms.mapper.AttendAdminMapper;
import com.etms.mapper.AttendMapper;
import com.etms.mapper.RepertoryMapper;
import com.etms.mapper.TuihuoMapper;
import com.etms.pojo.*;
import com.etms.service.*;
import com.etms.utils.DateUtils;
import com.etms.utils.IdUtils;
import com.etms.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    RepertoryMapper repertoryMapper;
    @Autowired
    HuopinService huopinService;
    @Autowired
    DeptService deptService;
    @Autowired
    SupplierService supplierService;
    @Autowired
    StatusService statusService;
    @Autowired
    CustomerService customerService;
    @Autowired
    AttendMapper attendMapper;
    @Autowired
    ThreadService threadService;
    @Autowired
    TuihuoMapper tuihuoMapper;
    @Autowired
    AccountsService accountsService;

    @Override
    public Result getList(PageParmas pageParmas) {
        PageHelper.startPage(pageParmas.getCurrentPage(), pageParmas.getPageSize());
        List<Repertory>list=null;
        if(pageParmas.getQueryMsg().length()>0&&pageParmas.getQueryMsg()!=""&&pageParmas.getQueryMsg()!="0"){
            list=repertoryMapper.findAllAdmin(pageParmas.getQueryMsg());
        }
        else
        list=repertoryMapper.findAllAdmin(pageParmas.getQueryMsg());
        PageInfo pageInfo=new PageInfo(list);
        PageResult pageResult=new PageResult();
        List<RepertoryVo>repertoryVolist=copyList(list);
        pageResult.setList(repertoryVolist);
        pageResult.setTotalPage(pageInfo.getPages());
        return Result.successed(pageResult);
    }


    @Override
    public Result getTuiList() {
        List<Tuihuo> list = tuihuoMapper.findAllAdmin();
        List<TuihuoVo>tuihuoVos=new ArrayList<>();
        for (Tuihuo tuihuo : list) {
            TuihuoVo tuihuoVo=new TuihuoVo();
            BeanUtils.copyProperties(tuihuo,tuihuoVo);
//            tuihuoVo.setIspass(false);
            tuihuoVo.setStatus(statusService.findById(tuihuo.getSid()));
            tuihuoVos.add(tuihuoVo);
        }
        return Result.successed(tuihuoVos);
    }

/*
    @Override
    public Result yeRe(Integer id, Integer uid) {
        //批准出入库,需要更新工作量以及修改库存信息,账目也要进行更新
        //批准出入库,更新工作量，修改库存信息,将信息提供给账目管理表(插入)，并且更新状态
        Repertory repertory = repertoryMapper.findById(id);
        Integer ruChu = repertory.getRuChu();//1入2出
        long sum = repertory.getSum();//数量
        Integer gid = repertory.getGid();//库存号id
        Integer sid = repertory.getSid();//状态码id
        Goods_status status = statusService.findById(sid);
        Goods_category kucn = (Goods_category) huopinService.findById(gid).getData();
        Double perPrice = kucn.getPerPrice();
        Double sumPrice = kucn.getSumPrice();//总价值
        long nowsum=0;
        long presum = kucn.getSum();
        Double nowmoney=0.0;
        Accounts accounts=accountsService.findById(1);
        Double premoney=accounts.getPrice();
        String msg=status.getAttr();
        if (ruChu==1){//入库 增加库存量,同时公司账户(老板)减去成本价*总量
            nowsum=presum+sum;
            nowmoney=premoney-(sum*perPrice);
            double v = sum * perPrice;
            BigDecimal d1 = new BigDecimal(Double.toString(v));
            msg+="  账户减去"+(d1)+"元";
        }
        if(ruChu==2){//出库 减少库存量,公司账户增加总价
            nowsum=presum-sum;
            if(nowsum<0){
                return Result.failed("库存已不足,请先补货!!");
            }
            nowmoney=premoney+sumPrice;
            BigDecimal d1 = new BigDecimal(Double.toString(sumPrice));
            msg+="  账户增加"+(d1)+"元";
        }
        if(accountsService.updateMoney(premoney,nowmoney,accounts.getId())==0){
            return Result.failed("入库失败,请检查公司余额!");
        }
        if(huopinService.updateSum(presum,nowsum,gid)>0){
            repertory.setPass(true);//批准
            repertoryMapper.updateIspass(id);//更新为批准状态
        }
        else {
            return Result.failed("批准失败!");
        }
        threadService.updateAttend(attendMapper,uid);//更新工作量
        threadService.insertMsg(accountsService,msg);//更新账户日志
        return Result.successed("成功批准!",null);
    }
*/
@Autowired
AttendAdminMapper attendAdminMapper;
    public Result yeRe(Integer id, Integer uid){
        //批准出入库,需要更新工作量以及修改库存信息,账目也要进行更新
        //批准出入库,更新工作量，修改库存信息,将信息提供给账目管理表(插入)，并且更新状态
        Repertory repertory = repertoryMapper.findById(id);
        Integer ruChu = repertory.getRuChu();//1入2出
        long sum = repertory.getSum();//数量
        Integer gid = repertory.getGid();//库存号id
        Integer sid = repertory.getSid();//状态码id
        Goods_status status = statusService.findById(sid);
        Goods_category kucn = (Goods_category) huopinService.findById(gid).getData();
        Double perPrice = kucn.getPerPrice();
        Double sumPrice = kucn.getSumPrice();//总价值
        long nowsum=0;
        long presum = kucn.getSum();
        Double nowmoney=0.0;
        Accounts accounts=accountsService.findById(1);
        Double premoney=accounts.getPrice();
        String msg=status.getAttr();
        AccountAdmin accountAdmin=new AccountAdmin();
        accountAdmin.setReid(id);
        accountAdmin.setUpdateTime(DateUtils.getDateTime(new Date()));
        accountAdmin.setUpdateTimeMils(DateUtils.getTimeMills(new Date()));

        if (ruChu==1){//入库 增加库存量,同时公司账户(老板)减去成本价*总量
            nowsum=presum+sum;
            double v = perPrice * sum;
            accountAdmin.setAddOrSub(2);//1+ 2-
            accountAdmin.setNeedToUpdate(v);//设置需要更新费用
            accountAdmin.setOwePrice(v);//设置欠费
            accountAdmin.setFactToUpdate(0.0);//初始化为0
            msg+="->账户需付费"+(v)+"元";
        }
        if(ruChu==2){//出库 减少库存量,公司账户增加总价
            nowsum=presum-sum;
            double v = perPrice * sum;
            accountAdmin.setAddOrSub(1);//1+
            accountAdmin.setNeedToUpdate(v);//设置需要更新费用
            accountAdmin.setOwePrice(v);//设置需要收费
            accountAdmin.setFactToUpdate(0.0);//初始化为0
            msg+="->账户需收费"+(v)+"元";
        }
        if(huopinService.updateSum(presum,nowsum,gid)>0){
            repertory.setPass(true);//批准
            repertoryMapper.updateIspass(id);//更新为批准状态
        }
        else {
            return Result.failed("批准失败!库存量问题!");
        }
        accountAdmin.setMsg(msg);
        repertoryMapper.updateIspass(id);//更新为批准状态
        threadService.updateAttend(attendMapper,uid);//更新工作量
        threadService.insertAD(attendAdminMapper,accountAdmin);//插入新表
        return Result.successed("成功批准!等待记账员管理账户信息",null);
    }
    @Override
    public Result noRe(Integer id, Integer uid) {//否决出入库,删掉该订单信息
        boolean f = repertoryMapper.delById(id);
        if(!f){
            return Result.failed("莫名错误");
        }
        threadService.updateAttend(attendMapper,uid);//更新工作量
        return Result.successed("否决成功",null);
    }

    @Override
    public Result yesTui(Integer id, Integer uid) {//批准退货,总量不用变,但是账户要变,需要判断是部分退货还是整单退货
        Tuihuo tuihuo = tuihuoMapper.findById(id);
        Integer counts = tuihuo.getCounts();
        if (counts!=-1){//部分退货
            return partTui(id,uid);
        }
        Integer ruChu = tuihuo.getRuChu();//1入2出,入库退货的话账户不变 出库退货表示客户退货,则需要减去这笔货的总值
        Integer sid = tuihuo.getSid();
        Goods_status status = statusService.findById(sid);
        String msg=status.getAttr();
        if(ruChu==2){
            Integer reId = tuihuo.getReId();
            Repertory repertory = repertoryMapper.findById(reId);
            Integer gid = repertory.getGid();//库存号id
            Goods_category kucn = (Goods_category) huopinService.findById(gid).getData();
            Double sumPrice = kucn.getSumPrice();//总价值
            Accounts accounts=accountsService.findById(1);
            Double premoney=accounts.getPrice();
            Double nowmoney=premoney-sumPrice;
            BigDecimal d1 = new BigDecimal(Double.toString(sumPrice));
            msg+="  账户减去"+(d1)+"元";
            Integer in = accountsService.updateMoney(premoney, nowmoney, 1);
            if(in==0){
                return Result.failed("退货失败!可能是公司账户余额不足");
            }

        }
        if(tuihuoMapper.updateIsPass(id)>0){
            threadService.updateAttend(attendMapper,uid);//更新工作量
            threadService.insertMsg(accountsService,msg);//更新账目日志
            return Result.successed("批准退货成功!",null);
        }
        return Result.failed("莫名错误");
    }

    private Result partTui(Integer tuiId, Integer uid) {//部分退货
        Tuihuo tuihuo = tuihuoMapper.findById(tuiId);
        Integer counts = tuihuo.getCounts();
        Integer ruChu = tuihuo.getRuChu();//1入2出,入库退货的话账户不变 出库退货表示客户退货,则需要减去这笔货的总值
        Integer sid = tuihuo.getSid();
        Goods_status status = statusService.findById(sid);
        String msg=status.getAttr();
        Integer reId = tuihuo.getReId();
        Repertory repertory = repertoryMapper.findById(reId);
        if(ruChu==2){//出库退货，即客户退货,则需要减去这笔货的退货量*单价
            Integer gid = repertory.getGid();//库存号id
            Goods_category kucn = (Goods_category) huopinService.findById(gid).getData();
            Double perPrice = kucn.getPerPrice();//单价
//            Double sumPrice = kucn.getSumPrice();//总价值
            Double sumPrice=perPrice*counts;
            Accounts accounts=accountsService.findById(1);
            Double premoney=accounts.getPrice();
            Double nowmoney=premoney-sumPrice;
            String d1 = IdUtils.doubleToString(sumPrice);
            msg+="  账户减去"+(d1)+"元";
            Integer in = accountsService.updateMoney(premoney, nowmoney, 1);
            if(in==0){
                return Result.failed("退货失败!可能是公司账户余额不足");
            }
        }
        if(tuihuoMapper.updateIsPass(tuiId)>0){//更新退货单状态并且更新订单的数量
            repertory.setSum(repertory.getSum()-counts);
            repertoryMapper.update(repertory);//更新订单的数量
            threadService.updateAttend(attendMapper,uid);//更新工作量
            threadService.insertMsg(accountsService,msg);//更新账目日志
            return Result.successed("批准退货成功!",null);
        }
        return Result.failed("莫名错误");
    }

    @Override
    public Result noTui(Integer id, Integer uid) {//否决退货,删掉退货订单信息
        int f = tuihuoMapper.delById(id);
        if(f==0){
            return Result.failed("莫名错误");
        }
        threadService.updateAttend(attendMapper,uid);//更新工作量
        return Result.successed("否决成功",null);
    }

    private List<RepertoryVo> copyList(List<Repertory> list) {
        List<RepertoryVo> copyList=new ArrayList<>();
        for (Repertory repertory : list) {
            RepertoryVo repertoryVo=copy(repertory);
            copyList.add(repertoryVo);
        }
        return copyList;
    }

    private RepertoryVo copy(Repertory repertory) {
        RepertoryVo vo=new RepertoryVo();
        BeanUtils.copyProperties(repertory,vo);
        Integer gid = repertory.getGid();//分类id
        Integer ddId = repertory.getDdId();//总部门id
        Integer deptId = repertory.getDeptId();//部门id
        Integer gongId = repertory.getGongId();//供货商id
        Integer keId = repertory.getKeId();//客户id
        Integer sid=repertory.getSid();//状态属性id
        Integer wId = repertory.getWId();
        Supplier supplier=new Supplier();
        Customer customer=new Customer();
        Goods_category good= (Goods_category) huopinService.findById(gid).getData();
        Dept dept=new Dept();
        if(ddId==1){
            dept=deptService.findCaiById(deptId);
        }else
            dept=deptService.findShengById(deptId);
        if(gongId!=null){
            supplier=supplierService.findById(gongId);
        }else supplier.setName("当前类型为自产入库");
        if(keId!=null)customer=customerService.findById(keId);

        Goods_status goods_status=statusService.findById(sid);
        vo.setGood(good).setDept(dept).setSupplier(supplier).setCustomer(customer).setStatus(goods_status).setWid(wId);
        vo.setTotalPrice(IdUtils.doubleToString(good.getPerPrice()*repertory.getSum()));
        return vo;
    }
}
